<template>
  <div class="app">
    <!-- 顶部导航 -->
    <el-row style="margin-bottom: 20px; align-items: center;">
      <el-button type="primary" icon="el-icon-arrow-left" @click="changeWeek(-1)">上一周</el-button>
      <span style="margin: 0 20px;">
      {{ formatDateRange(currentWeekStart, currentWeekEnd) }} （第{{ currentWeekNumber }}周）
      </span>
      <el-button type="primary" icon="el-icon-arrow-right" @click="changeWeek(1)">下一周</el-button>
      <el-button type="success" style="margin: 0 20px;" @click="handlePrint">打印表格</el-button>
      <span style="margin: 0 20px;">科室：</span>
      <el-select
        v-model="keshia"
        class="input"
        clearable
        placeholder="请选择"
        filterable
        @change="queryUser"
      >
        <el-option
          v-for="item in list_atl"
          :key="item.id"
          :label="item.department_name"
          :value="item.department_code"
        />
      </el-select>
      <el-button type="success" style="margin: 0 20px;" @click="save">保存</el-button>

      <!-- 新增选项按钮 -->
      <el-button type="primary" style="margin: 0 20px;" @click="addOption">新增选项</el-button>

      <el-button type="success" style="margin: 0 20px;" @click="optionListDialog = true;">
        查询选项列表
      </el-button>
    </el-row>

    <div ref="tableArea" class="print-area" style="margin-top: 20px;">
      <el-table
        :data="tableData"
        border style="width: 100%;"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="row => true"
        ></el-table-column>
        <el-table-column prop="groupString" label="组" width="70" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.groupString"
              size="small"
              @change="handleCellChange(scope.$index, 'groupString', scope.row.groupString)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="jobNumber" label="工号" width="80" align="center"></el-table-column>
        <el-table-column prop="userName" label="姓名" width="80" align="center"></el-table-column>
        <el-table-column
          v-for="(date, index) in weekDates"
          :key="index"
          :prop="date.field"
          :label="formatTableHeader(date)"
          align="center"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row[date.field]"
              size="small"
              @change="handleCellChange(scope.$index, date.field, scope.row[date.field])"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.optionName"
                :value="item.optionName"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.notes"
              size="small"
              @change="handleCellChange(scope.$index, 'notes', scope.row.notes)"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <!--      <div class="paging">-->
      <!--        <el-pagination-->
      <!--          :current-page="start"-->
      <!--          :page-size="PageSize"-->
      <!--          :pager-count="5"-->
      <!--          layout="total, sizes, prev, pager, next, jumper"-->
      <!--          :total="totalCount"-->
      <!--          @size-change="handleSizeChange"-->
      <!--          @current-change="handleCurrentChange"-->
      <!--        />-->
      <!--      </div>-->

      <!-- 新增选项对话框 -->
      <el-dialog title="新增选项" :visible.sync="optionsVisible" width="40%" :before-close="handleClose">
        <el-form ref="form" :model="newOption" :rules="rules">
          <el-form-item label="选项名称" :label-width="formLabelWidth">
            <el-input v-model="newOption.optionName" placeholder="请输入选项名称"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirmAddOption">确认</el-button>
        </div>
      </el-dialog>

      <!-- 查询选项对话框 -->
      <el-dialog title="查询选项列表" :visible.sync="optionListDialog" width="30%">
        <el-table :data="options" border stripe style="width: 100%">
          <el-table-column prop="optionName" label="选项名称"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="editType(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="deleteType(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {addOption, deleteOption, getOption, getZpaibanByYearAndWeekNumber, saveZpaibans} from "@/api/Zpaiban";
import {departmentDictionaryqueryList, usergetList} from "@/api/table";
import {deleteSqlType} from "@/api/ZSqlSettings";

export default {
  data() {
    return {
      // optionList: [],
      optionListDialog: false,
      formLabelWidth: '80px',
      initialNewOption: {
        id: "",
        optionName: "",
      },
      newOption: {
        id: "",
        optionName: "",
      },
      options: [],
      rules: {
        optionName: [
          {required: true, message: '请输入选项名称', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ],
      },
      list_atl: [],
      keshia: "",
      currentWeekStart: this.getWeekStart(new Date()),
      currentWeekEnd: this.getWeekEnd(new Date()),
      currentYear: new Date().getFullYear(),
      currentWeekNumber: this.getWeekNumber(new Date()),
      tableData: [],
      dialogVisible: false,
      optionsVisible: false,
      dialogTitle: "",
      selectedRows: [],
      formData: {},
      // start: 1,
      // totalCount: 0, // 总条数，根据接口获取数据长度(注意：这里不能为空)
      // pgeSizes: [10, 20, 30, 40], // 个数选择器（可修改）
      // PageSize: 10, // 默认每页显示的条数（可修改）
      departmentName: ""
    };
  },
  computed: {
    weekDates() {
      const dates = [];
      let start = new Date(this.currentWeekStart);
      for (let i = 0; i < 7; i++) {
        const date = new Date(start);
        dates.push({
          year: date.getFullYear(),
          date: `${date.getMonth() + 1}.${date.getDate()}`,
          day: this.getDayName(date),
          field: this.getDayField(i),
        });
        start.setDate(start.getDate() + 1);
      }
      console.log("========", dates)
      return dates;
    },
  },
  mounted() {
    departmentDictionaryqueryList().then((res) => {
      this.list_atl = res.data;
    });
    this.searchOption()
  },
  methods: {
    searchOption() {
      getOption().then(response => {
        this.options = response.data;
      })
    },
    deleteType(row) {
      this.$confirm('此操作将删除该类型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(
        () => {
          deleteOption(row.id).then(response => {
            this.searchOption()
            if (response.code !== 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          })
        }
      )
    },
    editType(row) {
      this.newOption = row;
      this.optionsVisible = true;
    },
    resetNewOption() {
      this.newOption = {...this.initialNewOption};
      console.log(this.newOption);
    },
    handleClose() {
      this.optionsVisible = false;
      this.resetNewOption();
    },
    addOption() {
      this.optionsVisible = true;
    },
    confirmAddOption() {
      if (this.newOption.id) {
        addOption({
          id: this.newOption.id,
          optionName: this.newOption.optionName,
        }).then(response => {
          this.searchOption()
          this.resetNewOption()
          if (response.code !== 1) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          }
        })
        this.optionsVisible = false;
      } else {
        addOption({
          optionName: this.newOption.optionName,
        }).then(response => {
          this.searchOption()
          this.resetNewOption()
          if (response.code !== 1) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
          }
        })
        this.optionsVisible = false;
      }
    },
    //查询当前周数据
    queryData() {
      getZpaibanByYearAndWeekNumber({
        year: this.currentYear,
        weekNumber: this.currentWeekNumber,
        keshi: this.departmentName,
        // size: PageSize,
        // start: start,
      }).then(res => {
        console.log(res)
        if (res.data.length === 0) {
          this.list()
        } else {
          this.tableData = res.data
        }
      })
    },
    save() {
      saveZpaibans(this.tableData)
    },
    queryUser() {
      // this.start = 1;
      const ctl = this.list_atl.find(item => item.department_code === this.keshia);
      if (ctl !== null && ctl !== undefined && ctl !== "") {
        console.log("科室已经选择: ", ctl.department_name)
        this.departmentName = ctl.department_name;
        this.queryData()
      } else {
        this.tableData = []
        this.totalCount = 0;
      }
      // this.list(this.PageSize, this.start);
    },
    list() {
      var deptCode = "";
      if (this.keshia !== "") {
        deptCode = this.keshia.replace(/\b(0+)/gi, "");
      } else {
        return
      }
      usergetList({
        deptCode: deptCode,
        // size: n1,
        // start: n2,
      }).then((res) => {
        this.tableData = res.data.map((item) => {
          console.log(item)
          return {
            id: "",
            year: this.currentYear,
            weekNumber: this.currentWeekNumber,
            keshi: this.departmentName,
            groupString: "",
            jobNumber: item.work_number,
            userName: item.user_name,
            monday: "",
            tuesday: "",
            wednesday: "",
            thursday: "",
            friday: "",
            saturday: "",
            sunday: "",
            notes: "",
          }
        });
        this.totalCount = res.totalCount;
      });
    },
    handleCellChange(index, field, value) {
      // 处理单元格变化事件
      console.log(`Row ${index}, Field ${field}, Value ${value}`);

      // 更新 tableData 中的数据
      this.$set(this.tableData[index], field, value);

      // 你可以在这里添加保存数据到服务器或其他逻辑
      this.saveDataToServer(index, field, value);
    },
    saveDataToServer(index, field, value) {
      // 示例：发送数据到服务器
      const row = this.tableData[index];
      const dataToSend = {
        jobNumber: row.jobNumber,
        [field]: value
      };
    },
    // 计算当前日期是该年的第几周
    getWeekNumber(date) {
      const newStart = this.getWeekStart(date);
      const firstDayOfYear = new Date(newStart.getFullYear(), 0, 1);
      const days = Math.floor((newStart - firstDayOfYear) / (24 * 60 * 60 * 1000));
      return Math.ceil((days + 1) / 7);
    },
    getWeekStart(date) {
      const day = date.getDay() || 7;
      date.setDate(date.getDate() - (day - 1));
      return new Date(date.getFullYear(), date.getMonth(), date.getDate());
    },
    getWeekEnd(date) {
      const start = this.getWeekStart(date);
      start.setDate(start.getDate() + 6);
      return start;
    },
    changeWeek(offset) {
      const newStart = new Date(this.currentWeekStart);
      newStart.setDate(newStart.getDate() + offset * 7);
      this.currentWeekStart = newStart;
      this.currentWeekEnd = this.getWeekEnd(newStart);
      this.currentWeekNumber = this.getWeekNumber(newStart);
      this.queryData()
    },
    formatDateRange(start, end) {
      return `${start.getFullYear()}.${start.getMonth() + 1}.${start.getDate()} - ${end.getFullYear()}.${end.getMonth() + 1}.${end.getDate()}`;
    },
    getDayName(date) {
      const days = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
      return days[date.getDay() === 0 ? 6 : date.getDay() - 1];
    },
    getDayField(index) {
      const fields = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
      return fields[index];
    },
    formatTableHeader(date) {
      return `${date.year}.${date.date} ${date.day}`;
    },
    formatTableDate(date) {
      return `${date.year}.${date.date}`;
    },
    formatTableDay(date) {
      return ` ${date.day}`;
    },
    handleRowClick() {
    },
    handleSelectionChange(selected) {
      this.selectedRows = selected;
    },
    handlePrint() {
      // 动态生成打印表格内容
      const columns = [
        {prop: "groupString", label: "组", width: "60px"},
        {prop: "jobNumber", label: "工号", width: "80px"},
        {prop: "userName", label: "姓名", width: "120px"},
        ...this.weekDates.map((date) => ({
          prop: date.field,
          label: this.formatTableDate(date),
          subLabel: this.formatTableDay(date),
        })),
        {prop: "notes", label: "备注", width: "120px"},
      ];

      // 生成表格数据
      const tableRows = this.tableData.map((row) => {
        return columns
          .map((col) => {
            const value = row[col.prop];
            return `<td style="text-align: center;">${value || ""}</td>`;
          })
          .join("");
      });

      // 计算列宽
      const calculateColumnWidth = (label, subLabel) => {
        const baseWidth = 10; // 基础宽度
        const charWidth = 8; // 每个字符的平均宽度
        const labelWidth = baseWidth + label.length * charWidth;
        const subLabelWidth = baseWidth + subLabel.length * charWidth;
        return `${Math.max(labelWidth, subLabelWidth)}px`;
      };

      const tableHeader = columns
        .map((col) => {
          if (col.subLabel) {
            return `<th style="width:${calculateColumnWidth(col.label, col.subLabel)}; text-align: center;">
          <div style="display: flex; flex-direction: column;">
            <span>${col.label}</span>
            <span>${col.subLabel}</span>
          </div>
        </th>`;
          } else {
            return `<th style="width:${calculateColumnWidth(col.label, "")}; text-align: center;">${col.label}</th>`;
          }
        })
        .join("");

      const tableHTML = `
  <table style="width: 100%; border-collapse: collapse; margin: 20px auto;">
    <thead>
      <tr style="background-color: #f2f2f2;">
        ${tableHeader}
      </tr>
    </thead>
    <tbody>
      ${tableRows.map((row) => `<tr>${row}</tr>`).join("")}
    </tbody>
  </table>
`;

      // 构建页头标题
      const year = this.currentWeekStart.getFullYear();
      const weekNumber = this.currentWeekNumber;
      const keshi = this.departmentName
      const headerTitle = `${keshi} ${year}年第${weekNumber}周排班表`;

      // 打开打印窗口
      const printWindow = window.open("", "_blank");
      printWindow.document.write("<html><head><title>打印表格</title>");
      printWindow.document.write(`
  <style>
    @page {
      size: A4 landscape;
      margin: 5mm 10mm 0 10mm; /* 上 右 下 左 */
    }
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }
    table {
      width: 100%;
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid #ccc;
      text-align: center;
      padding: 8px;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    th div {
      display: flex;
      flex-direction: column;
    }
  </style>
  `);
      printWindow.document.write("</head><body>");
      printWindow.document.write(`<h3 style='text-align: center;'>${headerTitle}</h3>`);
      printWindow.document.write(tableHTML);
      printWindow.document.write("</body></html>");
      printWindow.document.close();
      printWindow.print();
    }


  },
};
</script>


<style scoped>
.app {
  padding: 20px;
}

.row-selected {
  background-color: #e6f7ff !important;
}

.row-even {
  background-color: #f9f9f9; /* 偶数行背景色 */
}

.row-odd {
  background-color: #ffffff; /* 奇数行背景色 */
}

.paging {
  display: flex;
  justify-content: flex-end;
}
</style>
